﻿using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using Microsoft.Live;
using System.Xml;
using System.Xml.Serialization;
namespace SkyDriveAPI
{
    public  class SkyDriveInfo
    {
        public SkyDriveInfo()
        { 
        }
        public  string UserName = "sun.intex@hotmail.com";
        public string pwd = "msnmsnmsn";
        public string ApiKey = "00000000440E0BB5";
        public  string ApiSecret = "";
        public  string CallbackUrl = "";
        public string AccessToken = "EwA4Aq1DBAAUlbRWyAJjK5w968Ru3Cyt%2f6GvwXwAAcCvhbCXNvPJQmNzwdRjgfWz1Zjr7oi0zgbTTA3fge%2bGVW6Fj2B8Am7CKEM7yJ3qR3GvEXNDz1oASo97ryIzcAJoMs%2biYA2l%2fKzxsQeDqywj%2fsGE9DrA2NGfOZghFuFrDgiH22JPCvgE%2bOlhXNkn%2bjO7Tu%2bI4k%2bP0R8p%2bmqzSc5nCMFWHQYrOphjLoz%2bUgjtly7XRklUxNL%2byqOczsgiHaA%2bA%2br%2bZ9TeyQoEhyUCle2VMwLj%2fGmSf3NHhH09V%2bSfynsDRGG0lxsCIP2V4joJ915P%2bD%2bm%2fZThwoi3S0i899nv0qSxPahtbYjIB2OrnSKoYMdEE3MTNLebqGQlUbW4%2fKgDZgAACICFI7pjTi06CAFrUUO2zlwse0uyf2GHfeww5jkfmehegPDbltw0IjTisR2wMJludkrQVgwgF9aSU6z0H0h4O%2bV8VqK3fBrd2afTaDwwks808%2bx3oIMqcJPLXtvNVjKQ%2f43LVsVlRGo7%2bFmAIWWqv3q0GqHSmxz46Pc8Brm09uRduQ9ugd%2b6gZFRGXkxAkbyj9pXNTqnbtJaOPE%2be3CTTH8Hg6wUGyuOERiz9k5i0DHKzedDBnxukA8PcQAkRgcbcO4MY6cygY21zUr6zCtBffcrP0VqUXfEO4MiyMJS%2bjkfYcYZy%2bQPijOULFVRyRKffDOR4GXpCvC6y6xAPTk1jZdyY054yaCc6d7BkgVTUHVZRkoAAA%3d%3d&token_type=bearer&expires_in=3600&scope=wl.basic%20wl.photos%20wl.skydrive%20wl.offline_access%20wl.signin%20wl.skydrive_update";
        public  string RefreshToken = "";
        public string scope = "wl.basic wl.photos wl.skydrive wl.offline_access wl.signin wl.skydrive_update";
        public string expires_in = "36000000";
        public string token_type = "bearer";

    }
    public class SkyDriveFile
    {
        #region Vars and Props
        public string Token { get; set; }
        public bool IsSignIn { get; set; }
        private BackgroundWorker[] workers = new BackgroundWorker[GlobalMembers.MaxThread];
        LiveConnectSession Session; 
        #endregion
        public SkyDriveFile()
        {
            try
            {    
            }
            catch (Exception ex)
            {
             
            }
            finally
            {
              
            }
        }
        #region Upload
        private void initWorkers()
        {
            for (int i = 0; i < workers.Length; i++)
            {
                workers[i] = new BackgroundWorker();
                workers[i].DoWork += new DoWorkEventHandler(worker_DoWork);
                workers[i].RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
                workers[i].ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
                workers[i].WorkerReportsProgress = true;
                workers[i].WorkerSupportsCancellation = true;
            }
        }
        [SuppressMessage("Microsoft.Performance", "CA1811")]
        public void Upload(string filepath)
        {
            FileInfo file=new FileInfo(filepath);
            UploadItem item = new UploadItem(file, 1);
            UploadFile(GlobalMembers.RequestUrl, item.ItemInfo.OpenRead(), item.ItemInfo.Name, item.ThreadId);      
        }
        /// <summary>
        /// Upload file asynchronously by POST
        /// </summary>
        /// <param name="requestUrl">Url to upload to</param>
        /// <param name="data">File stream</param>
        /// <param name="fileName">File name</param>
        /// <param name="id">Thread id</param>
        [SuppressMessage("Microsoft.Performance", "CA1811")]
        private void UploadFile(string requestUrl, Stream data, string fileName, int id)
        {
            UriBuilder ub = new UriBuilder(requestUrl);
            ub.Query = string.Format(CultureInfo.InvariantCulture, GlobalMembers.UriBuilderQuery, Token);
            WebClient wc = new WebClient();
            wc.Headers[GlobalMembers.WebClientHeaderName] = GlobalMembers.WebClientHeaderValue;

            wc.OpenWriteCompleted += (sender, e) =>
            {
                if (!workers[id].IsBusy)
                    workers[id].RunWorkerAsync(new ThreadData { Id = id, FileName = fileName, Input = data, Output = e.Result });
            };

            wc.OpenWriteAsync(ub.Uri);
        }

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                ThreadData data = e.Argument as ThreadData;

                byte[] buffer = new byte[255];
                int bytesRead;
                double totalBytesRead = 0;
                double totalSize = data.Input.Length;

                // Add header 
                UTF8Encoding encoding = new UTF8Encoding();
                Byte[] bytes = encoding.GetBytes(GlobalMembers.StreamHeaderBoundaryStart +
                                                 GlobalMembers.StreamHeaderContentDisposition + data.FileName +
                                                 GlobalMembers.StreamHeaderContentType);
                data.Output.Write(bytes, 0, bytes.Length);

                // Write the file content
                while ((bytesRead = data.Input.Read(buffer, 0, buffer.Length)) != 0)
                {
                    data.Output.Write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                    System.Threading.Thread.Sleep(10);
                    workers[data.Id].ReportProgress((int)((totalBytesRead / totalSize) * 100), data.FileName);
                }

                // Close the boundary
                bytes = encoding.GetBytes(GlobalMembers.StreamHeaderBoundaryEnd);
                data.Output.Write(bytes, 0, bytes.Length);

                data.Input.Close();
                data.Output.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }
        }

        [SuppressMessage("Microsoft.Globalization", "CA1303")]
        private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
          
        }

        private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            for (int i = 0; i < workers.Length; i++)
            {
                if (workers[i].IsBusy)
                    return;
            } 
        }
        #endregion
    }
}
